
//simple example of moveable objects in processing 

float [] px = new float[4];
float [] py = new float[4];


//initialization of variables and setup - executed first
void setup() 
{
  
  size(600,400);//initialize window
  frameRate(30);
  
  //initialize position of 4 markers
  for (int i=0;i<4;i++)
  {
      px[i] = 100 + (i&1)*300;
      py[i] = 100 + int(i/2)*200;
  }
      
}


//main loop of the program
void draw() 
{
  //enable anti-aliasing so it looks neat
  smooth();
  
  //clear the background
  background(255);
 
  //pick a color and transparency
  fill(255,255,100,100);
  
  //display 4 markers
  for (int i=0;i<4;i++)
  {
      rect(px[i],py[i],20,20);
  }
  
  //display dots
  noStroke();
  fill(200,210,240);
  for (int x=0;x<width/20-1;x++)
    for (int y=0;y<height/20-1;y++)
    {
       //initial position of the dot 
       float xx = (x+1)*20;
       float yy = (y+1)*20;
       
       //compare it with positions of the markers
       for (int i=0;i<4;i++)
       {
         float d=dist(xx,yy,px[i],py[i]);
         if ((d<150)&&(d>0)) //if dot close enough to the marker
         {
           if (d<8) d=8;
           xx-=(px[i]-xx)/d*150/d;//modify position of the dot (affected by repulsion from the markers)
           yy-=(py[i]-yy)/d*150/d;
         }
       }
       
       //draw dot in final position
       ellipse(xx,yy,5,4);
    }
  stroke(0);
  
}


//that's a bit tricky - we intercept callback function (executed by the system whenever mouse is dragged)
//and we write our own code for it
void mouseDragged()
{
  for (int i=0;i<4;i++)
  {
      //if mouse cursor is inside of any of the squares
      if ((mouseX>=px[i])&&(mouseX<=px[i]+20)&&(mouseY>=py[i])&&(mouseY<=py[i]+20))
      {
        //move the square
        px[i] += mouseX-pmouseX; //update markers position
        py[i] += mouseY-pmouseY;
      }
  }
}



